<script setup lang="ts">
import dayjs from 'dayjs'
import { fetchAfterSalesDetailAPI } from '@/apis/fetchAfterSalesDetail'
import { fetchProjectDetailAPI } from '@/apis/fetchProjectDetail'
import { handleAfterSalesAPI } from '@/apis/handleAfterSales'
import { useProjectConfigStore } from '@/store/projectConfig'
import { useUserInfoStore } from '@/store/userInfo'

const router = useRouter()
const userInfoStore = useUserInfoStore()
const projectConfigStore = useProjectConfigStore()

/* ------------------------------ 待获取的数据 START ------------------------------ */
const afterSalesItem = ref<AfterSalesDetail | null>(null)
const project = ref<Project | undefined>(undefined)
/* ------------------------------- 待获取的数据 END ------------------------------- */

// 从路由参数中获取售后 id，并使用 id 请求详细数据。
onLoad(async (options) => {
  if (options && options.after_sales_item)
    afterSalesItem.value = JSON.parse(options.after_sales_item)
  else
    uni.showToast({ title: '获取数据失败', icon: 'none' })
})

onReady(() => {
  if (afterSalesItem.value?.status?.toString() === '1')
    uni.setNavigationBarTitle({ title: '待处理详情' })
  else if (afterSalesItem.value?.status?.toString() === '2')
    uni.setNavigationBarTitle({ title: '处理中详情' })
  else if (afterSalesItem.value?.status?.toString() === '3')
    uni.setNavigationBarTitle({ title: '已完成详情' })
})

onShow(async () => {
  try {
    const afterSalesRes = await fetchAfterSalesDetailAPI({
      id: afterSalesItem.value!.id!.toString()!,
    }, userInfoStore.userInfo!.token!)
    if (afterSalesRes.data?.code === 1)
      afterSalesItem.value = afterSalesRes.data.data

    const res = await fetchProjectDetailAPI(
      afterSalesItem.value!.project_id!.toString()!,
      userInfoStore.userInfo!.token!,
    )
    if (res.data?.code === 1)
      project.value = res.data?.data
  }
  catch {
    uni.showToast({ title: '获取数据失败', icon: 'none' })
  }
})

/* ------------------------------ 处理视图数据 START ------------------------------ */
const afterSalesStateDesc = computed(() => {
  if (userInfoStore.belongTo(['2'])) {
    if (afterSalesItem.value?.status?.toString() === '1')
      return '请及时处理业主提交的售后问题'
    else if (afterSalesItem.value?.status?.toString() === '2')
      return '售后处理中...'
    else if (afterSalesItem.value?.status?.toString() === '3')
      return '此售后申请已经处理完成'
  }
  else if (userInfoStore.belongTo(['0'])) {
    if (afterSalesItem.value?.status?.toString() === '1')
      return '您的售后申请已经提交，请耐心等待处理...'
    else if (afterSalesItem.value?.status?.toString() === '2')
      return '工长正在处理您发起的售后问题'
    else if (afterSalesItem.value?.status?.toString() === '3')
      return '您的售后申请已经处理完成'
  }
})

const copewithImages = computed(() => {
  if (afterSalesItem.value?.handle_images)
    return afterSalesItem.value.handle_images.split(',')
  else
    return []
})

const reasonImages = computed(() => {
  if (afterSalesItem.value?.images)
    return afterSalesItem.value?.images.split(',')
  else
    return []
})

function getTableInfo() {
  return [
    ['装修面积', '装修风格', '户型'],
    [project.value?.extent || '未知', project.value?.zx_style || '未知', project.value?.house_type_name || '未知'],
    ['装修类型', '工期截止', '项目总额'],
    [project.value?.project_type_name || '未知', project.value?.duration ? dayjs.unix(Number(project.value.duration)).format('YYYY.MM.DD') : '未知', { value: project.value?.money_total ? `¥${project.value.money_total}` : '未知', highlight: true }],
  ]
}

function getListInfo() {
  return [
    { label: '位置', value: `${project.value?.province}${project.value?.city}${project.value?.district}` },
    { label: '详细地址', value: project.value?.address || '未知', isShowNavigationButton: true },
    { label: '业务员', value: project.value?.salesman?.nickname || '未知' },
  ]
}
/* ------------------------------- 处理视图数据 END ------------------------------- */

/* ------------------------------- 事件处理 START ------------------------------- */
function handleCallContact() {
  if (project.value?.contacts_mobile) {
    uni.makePhoneCall({
      phoneNumber: project.value?.contacts_mobile,
      success: () => { },
      fail: () => { uni.showToast({ title: '呼叫取消', icon: 'none' }) },
    })
  }
}

function handleNavigation() {
  if (project.value?.latitude && project.value.longitude) {
    uni.openLocation({
      name: project.value.address,
      latitude: Number(project.value?.latitude),
      longitude: Number(project.value.longitude),
    })
  }
}

function handleTapContacts() {
  router.push({
    name: 'projectContacts',
    params: {
      project_id: project.value!.id!.toString()!,
    },
  })
}

function handleTapProjectNodes() {
  router.push({
    name: 'projectNodes',
    params: {
      project_id: project.value!.id!.toString()!,
    },
  })
}

async function handleCopewith() {
  if (afterSalesItem.value?.id) {
    try {
      const res = await handleAfterSalesAPI(afterSalesItem.value.id.toString(), userInfoStore.userInfo!.token!)
      if (res.data?.code === 1) {
        afterSalesItem.value.status = 2
        uni.showToast({ title: '处理成功', icon: 'none' })
      }
    }
    catch (err) {
      uni.showToast({ title: '处理失败', icon: 'none' })
    }
  }
  else {
    uni.showToast({ title: '处理失败', icon: 'none' })
  }
}

function handleUploadProof() {
  if (afterSalesItem.value?.id) {
    router.push({
      name: 'uploadProof',
      params: {
        after_id: afterSalesItem.value?.id.toString(),
      },
    })
  }
  else {
    uni.showToast({ title: '项目不存在', icon: 'none' })
  }
}
/* -------------------------------- 事件处理 END -------------------------------- */
</script>

<template>
  <Spacer height="30" />
  <view class="flex items-center text-28rpx leading-28rpx text-secondary">
    <image v-if="afterSalesItem?.status?.toString() === '1'" class="w-38rpx h-42rpx mr-12rpx" src="@/static/images/review-pending.png" />
    <image v-if="afterSalesItem?.status?.toString() === '2'" class="w-38rpx h-42rpx mr-12rpx" src="@/static/images/after-sales-2.png" />
    <image v-if="afterSalesItem?.status?.toString() === '3'" class="w-38rpx h-42rpx mr-12rpx" src="@/static/images/after-sales-3.png" />
    {{ afterSalesStateDesc }}
  </view>
  <Spacer height="20" />
  <ContactCard
    v-if="afterSalesItem?.status?.toString() === '1' || afterSalesItem?.status?.toString() === '2'"
    :contact-name="project?.contacts_name ? project.contacts_name : '未知'"
    contact-identity="业主"
    :contact-mobile="project?.contacts_mobile ? project.contacts_mobile : '未知'"
    @call="handleCallContact"
  />
  <Spacer v-if="afterSalesItem?.status?.toString() === '1' || afterSalesItem?.status?.toString() === '2'" height="30" />
  <view v-if="afterSalesItem?.status?.toString() === '3'" class="relative p-30rpx bg-white rounded-20rpx">
    <view class="absolute top-0 left-0 pt-3rpx pr-5rpx pb-4rpx pl-11rpx text-white text-24rpx leading-24rpx bg-#1DD67D rounded-tl-20rpx rounded-br-10rpx">
      {{ projectConfigStore.afterSalesStatusStr[afterSalesItem.status] || '未知' }}
    </view>
    <view class="flex items-center">
      <image
        class="w-72rpx h-72rpx bg-#F8F8F8 rounded-full"
        :src="project?.foreman?.avatar || 'http://jzt.tykhrs.cn/uploads/20240204/87b5977293b9856b96b77b21dcfc3e2a.png'"
      />
      <Spacer width="12" />
      <view class="flex flex-col">
        <view class="flex items-center mb-24rpx">
          <view class="text-28rpx leading-28rpx text-secondary">
            {{ project?.foreman?.nickname || '未知' }}
          </view>
          <Spacer width="12" />
          <view class="px-10rpx py-5rpx text-24rpx leading-24rpx text-brand bg-#FFEEE2 rounded-full">
            {{ '工长' }}
          </view>
        </view>
        <view class="text-28rpx leading-28rpx text-secondary">
          {{ project?.foreman?.mobile || '未知' }}
        </view>
      </view>
    </view>
    <Spacer height="40" />
    <Divider />
    <Spacer height="38" />
    <view class="text-secondary text-28rpx leading-40rpx">
      {{ afterSalesItem?.handle_desc || '无' }}
    </view>
    <Spacer v-if="copewithImages.length > 0" height="30" />
    <PictureGrid v-if="copewithImages.length > 0" mode="display" :width="630" :cols="3" :pictures="copewithImages" />
  </view>
  <Spacer v-if="afterSalesItem?.status?.toString() === '3'" height="30" />
  <view class="flex flex-col p-30rpx bg-white rounded-20rpx">
    <view class="text-30rpx leading-30rpx text-secondary font-bold">
      售后信息
    </view>
    <Spacer height="30" />
    <Divider />
    <Spacer height="38" />
    <view class="text-secondary text-28rpx leading-40rpx">
      {{ afterSalesItem?.desc }}
    </view>
    <Spacer v-if="reasonImages.length > 0" height="30" />
    <PictureGrid v-if="reasonImages.length > 0" mode="display" :width="630" :cols="3" :pictures="reasonImages" />
  </view>
  <Spacer height="30" />
  <view class="flex flex-col pt-30rpx px-30rpx pb-6rpx bg-white rounded-20rpx">
    <ProjectCardHeader
      :project-name="project?.name" :node-name="project?.node_name"
      :state="projectConfigStore.projectStatusStr[project?.status!]"
    />
    <Spacer height="20" />
    <Table :data="getTableInfo()" />
  </view>
  <Spacer height="30" />
  <ProjectInfoCard
    :info-list="getListInfo()"
    picture-label="合同照片"
    :pictures="project?.contract_images?.split(',') ? project?.contract_images?.split(',') : []"
    @navigate="handleNavigation"
  />
  <Spacer height="30" />
  <view class="flex flex-col p-30rpx bg-white rounded-20rpx">
    <view class="text-30rpx leading-30rpx text-secondary font-bold">
      项目功能
    </view>
    <Spacer height="30" />
    <Divider />
    <Spacer height="36" />
    <ProjectCardActions @tap-contacts="handleTapContacts" @tap-project-nodes="handleTapProjectNodes" />
  </view>
  <Spacer height="270" />
  <RGButton
    v-if="userInfoStore.belongTo(['2']) && afterSalesItem?.status?.toString() === '1'"
    class="fixed bottom-80rpx x-center"
    type="primary"
    @tap="handleCopewith"
  >
    点击处理
  </RGButton>
  <RGButton
    v-if="userInfoStore.belongTo(['2']) && afterSalesItem?.status?.toString() === '2'"
    class="fixed bottom-80rpx x-center"
    type="primary"
    @tap="handleUploadProof"
  >
    上传凭证
  </RGButton>
</template>

<route lang="yaml">
name: 'afterSalesDetail'
</route>
